package com.ra.util;

import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.googlecode.cswish.Config;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@SuppressWarnings("restriction")
public class RaImageUtils {

	private static final Log logger = LogFactory.getLog(RaImageUtils.class);
	
	// 租客端好好租水印地址
	private static final String HHZ_IMAGE_COMPOSITE_PATH = "/static/ra/rentNew/images/watermark.png";
	
	@Resource
	protected Config config;

	/**
	 * 图片截取
	 * 
	 * @param srcImg
	 *            源图片
	 * @param output
	 *            图片输出流
	 * @param rect
	 *            需要截取部分的坐标和大小
	 */
	public static void cutImage(File input, String newPath, Rectangle rect) {
		if (input.exists()) {
			FileInputStream fis = null;
			ImageInputStream iis = null;
			try {
				fis = new FileInputStream(input);

				// ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG,
				// JPEG, WBMP, GIF, gif]
				String types = Arrays.toString(ImageIO.getReaderFormatNames())
						.replace("]", ",");
				String suffix = null;
				// 获取图片后缀
				if (input.getName().indexOf(".") > -1) {
					suffix = input.getName().substring(
							input.getName().lastIndexOf(".") + 1);

				}
				// 类型和图片后缀全部小写，然后判断后缀是否合法
				if (suffix == null
						|| types.toLowerCase().indexOf(
								suffix.toLowerCase() + ",") < 0) {
					logger.error("Sorry, the image suffix is illegal. the standard image suffix is {}."
							+ types);
					return;
				}
				// 将FileInputStream 转换为ImageInputStream
				iis = ImageIO.createImageInputStream(fis);
				// 根据图片类型获取该种类型的ImageReader
				ImageReader reader = ImageIO.getImageReadersBySuffix(suffix)
						.next();
				reader.setInput(iis, true);
				ImageReadParam param = reader.getDefaultReadParam();
				param.setSourceRegion(rect);

				BufferedImage bufferedImage = null;
				try {
					if (input.canRead()) {
						bufferedImage = reader.read(0, param);
					}
				} catch (IOException e) {
					logger.error("read image", e);
				}

				if (bufferedImage != null) {
					File newPathFile = new File(newPath);
					newPathFile.getParentFile().mkdirs();
					ImageIO.write(bufferedImage, "jpg", new File(newPath)); // 保存修改后的图像,全部保存为JPG格式
				}
			} catch (FileNotFoundException e) {
				logger.error("图片截取出错！", e);
			} catch (IOException e) {
				logger.error("图片截取出错！", e);
			} finally {
				try {
					if (fis != null) {
						fis.close();
					}
					if (iis != null) {
						iis.close();
					}
				} catch (IOException e) {
					logger.error("图片截取出错！", e);
				}
			}
		} else {
			logger.warn("the src image is not exist.");
		}
	}

	public static void cutImage(File input, String newPath, int x, int y,
			int width, int height) {
		cutImage(input, newPath, new Rectangle(x, y, width, height));
	}

	/**
	 * @param input 原始图像
	 * @param newPath 新图片存储路径
	 * @param targetWidth 缩小宽度
	 * @param targetHeight 缩小高度
	 * @return 返回处理后的图像
	 */
	public static boolean zoomInImage(File input, String newPath, int targetWidth, int targetHeight) {
		BufferedImage result = null;
		boolean isWater = false;
		if(targetWidth == 510 && targetHeight == 340) {
			isWater = true;
		}
		try {
			BufferedImage originalImage = ImageIO.read(input);
			if (targetWidth > originalImage.getWidth() && targetHeight > originalImage.getHeight()) {
				return writeHighQuality(originalImage, newPath);
			} else {
				// calculate the scale
				float scaleWidth = (float)targetWidth / originalImage.getWidth();
				float scaleHeight = (float)targetHeight / originalImage.getHeight();
				float scale;
				if (scaleWidth < scaleHeight) {
					scale = scaleWidth;
					targetHeight = (int) (originalImage.getHeight() * scale);
				} else {
					scale = scaleHeight;
					targetWidth = (int) (originalImage.getWidth() * scale);
				}
				
				// zoom in
				result = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
				Graphics2D g = result.createGraphics();  
				g.drawImage(originalImage.getScaledInstance(targetWidth, targetHeight,  java.awt.Image.SCALE_SMOOTH), 0, 0, null);
				if(isWater) {
					// 图片水印处理
					int waterWidth = targetWidth;
					int waterHeight = targetHeight;
					if(targetWidth > originalImage.getWidth()) {
						waterWidth = originalImage.getWidth();
					}
					if(targetHeight > originalImage.getHeight()) {
						waterHeight = originalImage.getHeight();
					}
					waterImageHandle(waterWidth, waterHeight, g);
					g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); 
				}
				g.dispose();
				
				return writeHighQuality(result, newPath);
			} 
		} catch (Exception e) {
			logger.error("write image", e);
			return false;
		}
	}
	
	private static Graphics2D waterImageHandle(int width, int height, Graphics2D g) {
		// 图片水印处理
		Config config = Config.getInstance();
		String waterPath = config.getRealWebRootPath()
				+ HHZ_IMAGE_COMPOSITE_PATH;
		ImageIcon imgIcon = new ImageIcon(waterPath);

		// 得到Image对象
		Image imgWater = imgIcon.getImage();

		// 水印高宽
		int waterWidth = imgWater.getWidth(null);
		int waterHeight = imgWater.getHeight(null);
		
		/**
		 * 1、x，y分别表示水印图片在原始图片的位置 
		 * 2、width，height为商品图片的宽和高。 
		 * 3、width * 0.5表示水印图片的水平位置覆盖在商品图片水平位置的正中间。height * 0.5 表示垂直位置。
		 */
		int x = (int) (width * 0.1); // "0.5"小数越大，水印越向左移动。
		int y = (int) (height * 0.7); // "0.5"小数越大，水印越向上移动。

		// 透明度
		float alpha = 0.5f;
		g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
				alpha));

		// 表示水印图片的位置
		g.drawImage(imgWater, width - waterWidth - x, height - waterHeight - y,
				waterWidth, waterHeight, null);
		return g;
	}

	private static boolean writeHighQuality(BufferedImage result, String newPath) {
		try {
			File newPathFile = new File(newPath);
			newPathFile.getParentFile().mkdirs();
			
			// 输出到文件流 
			FileOutputStream newImage = new FileOutputStream(newPath);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newImage);
			JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(result);
			
			// 压缩质量 
			jep.setQuality(0.65f, true);
			encoder.encode(result, jep);
			
			newImage.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public static void main(String[] args) {
		File srcFile = new File("C:\\Users\\SK\\Desktop\\810x505-big-5f25ee629c5b4780bf9af78899c8e0fb.JPG");
		RaImageUtils.zoomInImage(srcFile, "C:\\Users\\SK\\Desktop\\123.JPG", 530, 340);
	}
}
